<template>
  <div class="dialog-admin">
    <el-dialog
      :visible.sync="dialogVisible"
      :title="field == 'add' ? '添加项目' : '修改项目'"
      width="800px"
      @close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="dialog-ruleForm"
      >
        <el-form-item label="所属企业:">
          <el-input v-model="ruleForm.deptName" :disabled="true" />
        </el-form-item>
        <el-form-item label="项目名称:" prop="itemName">
          <el-input v-model="ruleForm.itemName" clearable />
        </el-form-item>
        <el-form-item label="项目联系人:" prop="leader">
          <el-input v-model="ruleForm.leader" clearable />
        </el-form-item>
        <el-form-item label="联系电话:" prop="phone">
          <el-input v-model="ruleForm.phone" clearable />
        </el-form-item>
        <el-form-item label="项目地址:">
          <el-input
            v-model="ruleForm.itemAdress"
            clearable
            :disabled="true"
            style="width: 400px"
          />
          <el-button
            class="btn-search"
            icon="el-icon-location-outline"
            size="small"
            @click="handleClick"
          >
            选择
          </el-button>
        </el-form-item>
        <el-form-item label="建筑类型:">
          <el-select v-model="ruleForm.buildType" clearable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建筑面积:">
          <el-input v-model="ruleForm.buildArea" clearable>
            <span slot="suffix" style="padding-right: 10px">平方米</span>
          </el-input>
        </el-form-item>
        <el-form-item label="项目简介:">
          <el-input v-model="ruleForm.introduction" clearable />
        </el-form-item>
        <el-form-item label="备注信息:">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 4 }"
            clearable
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="addressDialog"
      title="地图选址"
      width="1000px"
      custom-class="mapDialog"
      @close="closeMapDialog"
    >
      <div>
        <GaodeMap @updateLocation="updateLocation" :addressDialog="addressDialog" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeMapDialog">取 消</el-button>
        <el-button type="primary" @click="parentConfirmFunction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import GaodeMap from "@/components/GaodeMap";
import { projectAdd, projectUpdate } from "@/api/projectmanagement";
import { mapGetters } from "vuex";
export default {
  name: "ProjectDetail",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    field: {
      type: String,
      default: "",
    },
    rowData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  components: { GaodeMap },
  data() {
    // 手机号校验规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入联系电话"));
      } else {
        const reg = /^1[3-9]\d{9}$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的手机号码"));
        } else {
          callback();
        }
      }
    };

    return {
      ruleForm: {},
      rules: {
        itemName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
          { max: 30, message: "项目名称不能超过30个字符", trigger: "blur" },
        ],
        leader: [{ required: true, message: "请输入项目联系人", trigger: "blur" }],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
      },
      addressDialog: false,
      selectedLocation: {
        itemAdress: "",
        location: "",
        province: "",
        city: "",
        district: "",
        township: "",
      },
      options: [],
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    dialogVisible: {
      get() {
        return this.value; // 返回父组件通过 v-model 传递的值
      },
      set(val) {
        this.$emit("close", val); // 当 dialogVisible 变化时，通知父组件更新
      },
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.ruleForm = { ...this.rowData };
        this.getBuildTypeOptions();
      }
    },
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
      this.$emit("close");
    },

    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.handleConfirm();
        } else {
          return false;
        }
      });
    },
    handleConfirm() {
      let data = {
        deptId: this.userInfo.deptId,
        deptName: this.ruleForm.deptName,
        itemName: this.ruleForm.itemName,
        leader: this.ruleForm.leader,
        phone: this.ruleForm.phone,
        itemAdress: this.ruleForm.itemAdress || "",
        location: this.ruleForm.location || "",
        province: this.ruleForm.province || "",
        city: this.ruleForm.city || "",
        district: this.ruleForm.district || "",
        township: this.ruleForm.township || "",
        buildType: this.ruleForm.buildType,
        buildArea: this.ruleForm.buildArea,
        introduction: this.ruleForm.introduction,
        remark: this.ruleForm.remark,
      };

      if (this.field == "add") {
        projectAdd(data).then((res) => {
          if (res.code == 0) {
            this.$message.success("添加成功");
            this.$emit("init");
            this.handleClose();
          }
        });
      } else {
        data.id = this.ruleForm.id;
        projectUpdate(data).then((res) => {
          if (res.code == 0) {
            this.$message.success("修改成功");
            this.$emit("init");
            this.handleClose();
          }
        });
      }
    },
    handleClose() {
      this.dialogVisible = false; // 关闭弹窗
      this.$emit("close"); // 发送关闭事件给父组件
    },
    handleClick() {
      this.addressDialog = true;
    },
    updateLocation(data) {
      this.selectedLocation = {
        itemAdress: data.address,
        location: data.longitudeLatitude,
        province: data.province,
        city: data.city,
        district: data.district,
        township: data.township,
      };
    },
    parentConfirmFunction() {
      this.ruleForm.itemAdress = this.selectedLocation.itemAdress;
      this.ruleForm.location = this.selectedLocation.location;
      this.ruleForm.province = this.selectedLocation.province;
      this.ruleForm.city = this.selectedLocation.city;
      this.ruleForm.district = this.selectedLocation.district;
      this.ruleForm.township = this.selectedLocation.township;
      this.addressDialog = false;
    },
    closeMapDialog() {
      this.addressDialog = false;
      this.selectedLocation = {
        itemAdress: "",
        location: "",
        province: "",
        city: "",
        district: "",
        township: "",
      };
    },
    // 获取建筑类型选项
    async getBuildTypeOptions() {
      try {
        // 调用 store 中的字典查询方法，传入字典类型
        const data = await this.$store.dispatch("dict/queryDictData", "sys_kt_buildType");
        // 根据接口返回的数据格式进行处理
        this.options = data.map((item) => ({
          value: item.dictValue,
          label: item.dictLabel,
        }));
      } catch (error) {
        this.$message.error("获取建筑类型数据失败");
      }
    },
  },
};
</script>
<style scoped lang="scss">
.dialog-ruleForm {
  width: 80%;
  line-height: 60px;
  margin: 0 auto;
}
</style>
<style lang="scss">
.mapDialog {
  margin-top: 5vh !important;
  .el-dialog__body {
    height: 700px;
    overflow: auto;
    padding-bottom: 15vh;
  }
}
</style>
